package com.fl.chinesemedicen;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ant.liao.GifView;
import com.bumptech.glide.Glide;
import com.fl.chinesemedicen.domain.Acupoint;
import com.fl.chinesemedicen.domain.BodyChannel;
import com.fl.chinesemedicen.domain.MyGridView;
import com.fl.chinesemedicen.util.Globals;
import com.fl.chinesemedicen.view.GifSurfaceView;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

public class MainActivity extends Activity {

    private ListView lvJL;
    private LinkedList<Acupoint> acupointLinkedList;
    private LinkedList<BodyChannel> bodyChannels;
    private ImageView iv;
    private GifSurfaceView ivPath;
    private RelativeLayout llPath;
    private Map<String,String> resources = new HashMap<>();
    private Handler handler;
    private Runnable runnable;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar = getActionBar();
        if(actionBar!=null){
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
            actionBar.setCustomView(R.layout.bar);
            iv = (ImageView) actionBar.getCustomView().findViewById(R.id.iv_bar);
            iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    RotateAnimation rotateAnimation = new RotateAnimation(0,720, Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
                    rotateAnimation.setDuration(2000);
                    iv.startAnimation(rotateAnimation);
                }
            });
        }
        ivPath = (GifSurfaceView) findViewById(R.id.iv_jl_path);
        handler = ivPath.getHandler();
        runnable = ivPath.getRunnable();
        llPath = (RelativeLayout) findViewById(R.id.ll_iv_path);
        llPath.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ivPath.setVisibility(View.GONE);
                llPath.setVisibility(View.GONE);
                //handler.removeCallbacks(runnable);
            }
        });
        llPath.setVisibility(View.GONE);
        //穴位集合
        acupointLinkedList = new LinkedList<>();
        //经络集合
        bodyChannels = new LinkedList<>();
        String fs = File.separator;
        //File file = new File(fs + "storage" + fs + "sdcard1" + fs+"XW.txt");
        InputStream file = null;
        InputStream JLFile = null;
        try {
            file = getAssets().open("XW.txt");
            JLFile = getAssets().open("JL.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //File JLFile = new File(fs + "storage" + fs + "sdcard1" + fs+"JL.txt");
        lvJL = (ListView) findViewById(R.id.lv_jl);
        readXW(file,new Acupoint(),acupointLinkedList);
        readJL(JLFile,new BodyChannel(),bodyChannels);
        lvJL.setAdapter(new MyListAdapter());
        resources.put("督脉","dumai.gif");
        resources.put("手太阴肺经","shoutaixinfeijing.gif");
        resources.put("任脉",".gif");
        resources.put("手厥阴心包经","手厥阴心包经.gif");
        resources.put("手太阴肺经","手太阴肺经.gif");
        resources.put("手少阳三焦经","手少阳三焦经.gif");
        resources.put("手少阴心经","手少阴心经.gif");
        resources.put("手阳明大肠经","手阳明大肠经.gif");
        resources.put("足厥阴肝经","足厥阴肝经.gif");
        resources.put("足太阳膀胱经","足太阳膀胱经.gif");
        resources.put("足太阴脾经","足太阴脾经.gif");
        resources.put("足少阳胆经","足少阳胆经.gif");
        resources.put("足少阴肾经","足少阴肾经.gif");
        resources.put("足阳明胃经","足阳明胃经.gif");




    }
    public void readJL(InputStream file , BodyChannel channelTMP, LinkedList<BodyChannel> bodyChannels){
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(file));
            String s = null;
            while((s = br.readLine())!= null){
                if(s.contains("$JLNAME$")){
                    BodyChannel bc = new BodyChannel();
                    channelTMP = bc;
                    channelTMP.setName(s.replace("$JLNAME$",""));
                }
                if(s.contains("$JLPATH$")){
                    channelTMP.setPath(s.replace("$JLPATH$",""));
                }
                if(s.contains("$JLDISEASE$")){
                    channelTMP.setDisease(s.replace("$JLDISEASE$",""));
                }
                if(s.contains("$ATTENDING$")){
                    channelTMP.setEffective(s.replace("$ATTENDING$",""));
                }
                if(s.contains("$CONTAINS$")){
                    String[] strs = s.replace("$CONTAINS$", "").split(",");
                    LinkedList<String> values = new LinkedList<>();
                    for (String str:strs) {
                        values.add(str);
                    }
                    channelTMP.setAcupointLinkedList(values);
                    channelTMP.setAcupointSizes(strs.length);
                    bodyChannels.add(channelTMP);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static String readXW(InputStream file, Acupoint acupointTMP, LinkedList<Acupoint> acupointLinkedList){
        StringBuilder result = new StringBuilder();
        try{
            BufferedReader br = new BufferedReader(new InputStreamReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                if(s.contains("$name$")){
                    Acupoint acupoint = new Acupoint();
                    acupointTMP = acupoint;
                    String name = s.replace("$name$","");//$position$ $effective$ $attending$ $clinical$
                    acupointTMP.setName(name);
                }
                if(s.contains("$position$")){
                    String pos = s.replace("$position$","");
                    acupointTMP.setPosition(pos);
                }
                if(s.contains("$waytoget$")){
                    String getway = s.replace("$waytoget$","");
                    acupointTMP.setWaytoget(getway);
                }
                if(s.contains("$effective$")){
                    String effective = s.replace("$effective$","");
                    acupointTMP.setEffective(effective);
                }
                if(s.contains("$attending$")){
                    String attending = s.replace("$attending$","");
                    acupointTMP.setAttending(attending);
                }
                if(s.contains("$clinical$")){
                    String cli = s.replace("$clinical$","");
                    acupointTMP.setClinical(cli);
                    acupointLinkedList.add(acupointTMP);
                }
            }
            br.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        return result.toString();
    }


    class MyListAdapter extends BaseAdapter{
        @Override
        public int getCount() {
            return bodyChannels.size();
        }

        @Override
        public Object getItem(int position) {
            return bodyChannels.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if(convertView == null){
                convertView = View.inflate(getApplicationContext(),R.layout.lv_jl_xw_item,null);
            }
            TextView tv = (TextView) convertView.findViewById(R.id.ll_tv_jl);
            tv.setText(bodyChannels.get(position).getName());
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String name = bodyChannels.get(position).getName();
                    System.err.println(name);
                    if(llPath.getVisibility() == View.GONE){
                        ivPath.setVisibility(View.VISIBLE);
                        llPath.setVisibility(View.VISIBLE);
                    }

                    ivPath.setPath(resources.get(name));
                    ivPath.setZoom(1);

                    //设置Gif图片源
                    //ivPath.setGifImage(resources.get(name));
                    //添加监听器
                    //ivPath.setOnClickListener(this );
                    //设置显示的大小，拉伸或者压缩
                    //ivPath.setShowDimension(300 , 300 );
                    //设置加载方式：先加载后显示、边加载边显示、只显示第一帧再显示
                    //ivPath.setGifImageType(GifView.GifImageType.COVER);
                }
            });
            MyGridView gv = (MyGridView) convertView.findViewById(R.id.ll_gv_xw);
            gv.setAdapter(new BaseAdapter() {
                @Override
                public int getCount() {
                    return bodyChannels.get(position).getAcupointLinkedList().size();
                }

                @Override
                public Object getItem(int gvposition) {
                    return bodyChannels.get(position).getAcupointLinkedList().get(gvposition);
                }

                @Override
                public long getItemId(int gvposition) {
                    return gvposition;
                }

                @Override
                public View getView(final int gvposition, View convertView, ViewGroup parent) {
                    if(convertView==null){
                        convertView = View.inflate(getApplicationContext(),R.layout.expand_child_item,null);
                    }
                    TextView tv = (TextView) convertView.findViewById(R.id.tv_xw);
                    tv.setText(bodyChannels.get(position).getAcupointLinkedList().get(gvposition));
                    tv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            for (Acupoint ac:acupointLinkedList) {
                                String str = bodyChannels.get(position).getAcupointLinkedList().get(gvposition).trim();
                                String name = ac.getName().trim();
                                Log.e("hahah",str+"------------------"+name);
                                if(str.equals(name)){
                                    Globals.ac = ac;
                                    Log.e("hahah",str+"------------------"+name);
                                    startActivity(new Intent(MainActivity.this,AcupointActivity.class));
                                    return;
                                }
                            }
                        }
                    });
                    return convertView;
                }
            });
            return convertView;
        }
    }












    class MyAdapter extends BaseExpandableListAdapter {
        @Override
        public int getGroupCount() {
            return bodyChannels.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return bodyChannels.get(groupPosition).getAcupointLinkedList().size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return bodyChannels.get(groupPosition);
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return bodyChannels.get(groupPosition).getAcupointLinkedList().get(childPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            if(convertView==null){
                convertView = View.inflate(getApplicationContext(),R.layout.expand_group_item,null);
            }
            TextView tv = (TextView) convertView.findViewById(R.id.tv_jl);
            tv.setText(bodyChannels.get(groupPosition).getName());
            TextView tvShow = (TextView) convertView.findViewById(R.id.tv_show_detail);
            tvShow.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(getApplicationContext(),bodyChannels.get(groupPosition).getPath(),Toast.LENGTH_SHORT).show();
                }
            });
            return convertView;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            if(convertView==null){
                convertView = View.inflate(getApplicationContext(),R.layout.expand_child_item,null);
            }
            TextView tv = (TextView) convertView.findViewById(R.id.tv_xw);
            tv.setText(bodyChannels.get(groupPosition).getAcupointLinkedList().get(childPosition));
            return convertView;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }


}
